/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: record_lib.c
 * Create Date: 2011-07-13 11:27:54
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "record_lib.h"
#include "conf_lib.h"
#include "mysql_lib.h"
#include "time_lib.h"

long dorecord(const char *sub, char *table){
	int isrecord = 0;
	long lastid;
	char *sql, *sqlescape, *logname, *isrec, *logdb, lgn[100], ctable[200];
	char usedb[100];
	MYSQL *sm_conn;

	logname = table;
	
	sprintf(lgn, "sql_log_%s", logname);

	isrec = conf_get("isrecord");
	logdb = conf_get("log_db");
	if(isrec)
		isrecord = atoi(isrec);
	
	if(isrecord){
		sm_conn = connect_sql();

		sqlescape = escape_mysql(sub, sm_conn);
		
		sprintf(usedb, "use %s;", logdb);
		query_mysql(usedb, sm_conn);

		if(-1 == list_table(lgn, sm_conn)){
			sprintf(ctable, "create table `%s`( `id` bigint(20) NOT NULL AUTO_INCREMENT,  `sql` text NOT NULL,  PRIMARY KEY (`id`));", lgn);
			query_mysql(ctable, sm_conn);
			commit_mysql(sm_conn);
		}
	
		sql = (char *)calloc(strlen(sqlescape)+500, sizeof(char));

		sprintf(sql, "INSERT INTO `%s`.`%s` (`sql`)VALUES ('%s');", logdb, lgn, sqlescape);	
		
		lastid = set_mysql(sql, sm_conn);

		free(sql);
		free(sqlescape);
		/*free(usedb);*/
	}
	/*free(logname);*/
	return lastid;
}

/* vim: set ts=4 sw=4: */
